package com.lagou.controller;

import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.service.AuthCodeService;
import com.lagou.service.EmailFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Optional;


@RestController
@RequestMapping(value = "/code")
public class CodeController {

    @Autowired
    private AuthCodeService authCodeService;

    @Autowired
    private EmailFeignClient emailFeignClient;


    /**
     * ⽣成验证码并发送到对应邮箱，成功true，失败
     * false
     * @param email
     * @return
     */
    @RequestMapping(value = "/create/{email}")
    public boolean create(@PathVariable(value = "email") String email) {
        //生成随机验证码
        Integer intCode = (int)(Math.random() * 9 + 1) * 100000;
        String code = intCode.toString();
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCreatetime(new Date());
        //过期时间：十分钟
        Date date = new Date();
        date.setMinutes(date.getMinutes() + 10);
        lagouAuthCode.setExpiretime(date);
        authCodeService.insert(lagouAuthCode);

        //TODO 调用email工程，将生成的验证码发送到用户邮箱中。
        return emailFeignClient.send(email, code);
    }


    /**
     * 校验验证码是否正确，0正确1错误2超时
     * @param email
     * @param code
     * @return
     */
    @RequestMapping(value = "/validate/{email}/{code}")
    public Integer validate(@PathVariable(value = "email") String email,
                            @PathVariable(value = "code") String code) {
        //根据email查询验证码
        Optional<LagouAuthCode> lagouAuthCode = authCodeService.fiddByEmail(email);
        if(lagouAuthCode != null) {
            LagouAuthCode lagouAuthCode1 = lagouAuthCode.get();
            //是否超时
            if(lagouAuthCode1.getExpiretime().compareTo(new Date()) == -1) {
                return 2;
            }
            //验证码是否正确
            if(code.equals(lagouAuthCode1.getCode())){
                return 0;
            }
        }
        return 1;
    }
}
